import { Channel } from '@/types/data.d.'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
// state变量类型
export interface homeState {
  channelList: Channel[]
  userChannel: Channel[]
  active: number
}
export const home = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'home',
  // 1. 定义变量(状态数据)
  initialState: {
    channelList: [],
    userChannel: [],
    // 当前选中频道的id
    active: 0
  } as homeState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    setChannelList(state, action: PayloadAction<Channel[]>) {
      state.channelList = action.payload
    },
    setUserChannelList(state, action: PayloadAction<Channel[]>) {
      state.userChannel = action.payload
    },
    setActive(state, action: PayloadAction<number>) {
      state.active = action.payload
    },
    delUserChannel(state, action: PayloadAction<Channel>) {
      // 我的频道删除
      state.userChannel = state.userChannel.filter(item => item.id !== action.payload.id)
      // 推荐新增频道 =》 我的删除的内容
      state.channelList.push(action.payload)
    },
    addUserChannel(state, action: PayloadAction<Channel>) {
      // 我的频道删除
      state.channelList = state.channelList.filter(item => item.id !== action.payload.id)
      // 推荐新增频道 =》 我的删除的内容
      state.userChannel.push(action.payload)
    },
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { setChannelList, setUserChannelList, setActive, delUserChannel, addUserChannel } = home.actions


// 导出reducer(创建store使用)
export default home.reducer